from commons import executeCommand
from admin.validationutils import ValidationUtils
import applicationproperties as properties
import re, os, platform

class NetworkUtils(object):
    
    UNKNOWN='UNKNOWN'
    UNKNOWN1='Ratnam'    
    def __init__(self):
        pass
    
    def getNetworkInfo(self):
        info = {}
        info['hostname'] = self.getHostName()
        info['domainname'] = self.getDomainName()
        info['default_iface'] = self.getDefaultIface()
        info['default_phyiface'] = self.getDefaultPhyIface()
        info['ipaddr'] = self.getIPAddress()
        info['subnet'] = self.getNetMask()
        info['gateway'] = self.getGateway()
        info['dns1'], info['dns2'] = self.getDNS()
        #info['dns2'] = self.getDNS2()
        info['dhcp'] = self.isDHCP()
        info['vlanid'] = self.getDefaultVlanID()
        info['mac'] = self.getMACAddress()
        info['sroutes'] = self.getStaticRoutes()
        info['vlans'] = self.getVlans()
        info['interfaces'] = self.getInterfaces()
        info['allinterfaces'] = self.getAllInterfaces()
        info['wanip'] = self.UNKNOWN
        info['phyInterfacesInfo'] = self.getPhyInterfacesInfo()
        #info['is_precise'] = True if platform.dist()[2] == 'precise' else False
        return info
    
    
    def isDHCP(self):
        try:
            return executeCommand("/bin/grep",['dhcp',properties.SYSCONFIG_IFCFG_ETH0], True)[0] == 0
        except:
            return False
    
    def getDefaultVlanID(self):
        vlan_id = ""
        default_iface = self.getDefaultIface()
        if not default_iface.find('.') == -1:
            vlan_id = default_iface.split('.')[1]
            if vlan_id.isdigit():
                return vlan_id.strip()
        return ""

    def getDefaultIface(self):
        try:
            result = executeCommand("/sbin/route -n | /bin/grep -e ^0.0.0.0 | /usr/bin/head -1 | /usr/bin/awk '{print $8}'")
            if result[1].strip() != "":
                return result[1].strip()
            else:
                return self.UNKNOWN
        except:
            return self.UNKNOWN
    
    def getDefaultPhyIface(self):
        try:
            result = executeCommand("/sbin/route -n | /bin/grep -e ^0.0.0.0 | /usr/bin/head -1 | /usr/bin/awk '{print $8}'")
            if result[1].strip() != "":
                return result[1].strip().split(".")[0]
            else:
                return ""
        except:
            return ""
    
    def getHostName(self):
        try:
            output = executeCommand('/bin/hostname -s')
            return output[1].strip()
        except:
            return self.UNKNOWN
    
    def getDomainName(self):
        try:
            output = executeCommand('/bin/hostname -d')
            return output[1].strip()
        except:
            return self.UNKNOWN
    
    def getIPAddress(self, iface=""):
        try:
            cmd = "/sbin/ifconfig eth0| grep 'inet addr:' | /usr/bin/awk '{print $2}'"
            ip = executeCommand(cmd)[1]
	    ip1 = ip.split(":")[1]
	    return ip1
        except:
            return self.UNKNOWN
    
    def getNetMask(self, iface=""):
        try:
            cmd = "/sbin/ifconfig eth0| grep 'inet addr:' | /usr/bin/awk '{print $4}'|/usr/bin/awk -F: '{print $2}'"
	    netmask = executeCommand(cmd)[1]
            return netmask
        except:
            return self.UNKNOWN
    
    def getGateway(self):
        try:
            output = executeCommand("/sbin/route -n | /bin/grep -e ^0.0.0.0 | /usr/bin/head -1 | /usr/bin/awk '{print $2}'")
            return output[1].strip()
        except:
            return self.UNKNOWN

    def getStaticRoutes(self):
        try:
            srouteArr = []
            routesArr = []
            output = executeCommand("/sbin/route -n | grep -v 'Kernel IP' | grep -v 'Destination' | grep -v '0.0.0.0'", [], True)
            if output[0] == 0:
                routesArr = output[1].strip().split("\n")
            for route in routesArr:
                route = re.sub(r"\s+"," ",route.strip())
                routeVals = route.split(" ")
                srouteArr.append([routeVals[0],routeVals[1],routeVals[2],routeVals[4],routeVals[7]])
            return srouteArr
        except:
            return []
        
    def getVlans(self):
        try:
            vlanArr = []
            interfaces=[]
            net_files = os.listdir("/sys/class/net")
            for d in net_files:
                path = os.path.join("/sys/class/net", d)
                if not os.path.isdir(path) or d.find('.') == -1:
                    continue
                interfaces.append(d)
      
            for iface in interfaces:
                vlan_id = iface.split('.')[1]
                vlan_ip = self.getIPAddress(iface)
                vlan_nm = self.getNetMask(iface)
                vlan_raw_device = iface.split('.')[0]
                vlanArr.append([vlan_id.strip(),vlan_ip.strip(),vlan_nm.strip(),vlan_raw_device.strip(),iface.strip()]) #vlan_iface argument is for deleting only. It will be always eth0.*
            return vlanArr
        except:
            return []
        
    def getPhyInterfacesInfo(self):
        try:
            phyArr = []
            for iface in self.getInterfaces():
                ip = self.getIPAddress(iface)
                nm = self.getNetMask(iface)
                #print  "iface.strip(),ip.strip(),nm.strip()"
                phyArr.append([iface.strip(),ip.strip(),nm.strip()]) #vlan_iface argument is for deleting only. It will be always eth0.*
            return phyArr
        except:
            return []
       
    
    def getInterfaces(self):
        '''
        try:
            interfaces = []
            for inum in range(2):
                cmd = properties.CMD_SUDO + " /sbin/ethtool eth" + str(inum) + " | /bin/grep -i 'Link detected: yes'"
                result = executeCommand(cmd, [], True)
                if result[0] == 0:
                    interfaces.append("eth" + str(inum))
            return interfaces
        except:
            return []
        '''
        
        try:
            interfaces = []
            net_files = os.listdir("/sys/class/net")
            for d in net_files:
                path = os.path.join("/sys/class/net", d)
                if not os.path.isdir(path) or not os.path.exists(os.path.join(path, "device")):
                    continue
                interfaces.append(d)
            return interfaces
        except:
            return []
            
    def getAllInterfaces(self):
        try:
            interfaces = []
            net_files = os.listdir("/sys/class/net")
            for d in net_files:
                path = os.path.join("/sys/class/net", d)
                if not os.path.isdir(path):
                    continue
                if d == "lo" or d == "virbr0" or d == "eth0" or d == "kvmbr0":
                    continue
                interfaces.append(d.strip())
            return interfaces
        except:
            return []
        
    def getDNS(self):
        try:
            ipCnt = 0
            dns1 = ""
            dns2 = ""
            cmd = "cat /etc/resolv.conf | /bin/grep nameserver | grep -v \";\" | grep -v \"#\""
            output = executeCommand(cmd)
            nameserverArr = output[1].split("\n")

           # utils = ValidationUtils()
            for line in nameserverArr:
                ip = line.strip().split(" ")[1].rstrip()
                #if utils.isValidIP(ip):
                ipCnt = ipCnt + 1
                if ipCnt == 1:
                	dns1 = ip
                #elif ipCnt == 2:
		else:
                        dns2 = ip
                	return dns1, dns2
                    
            return dns1, dns2
        except:
            return '', ''
    
        
    def getMACAddress(self):
        try:
            output = executeCommand("/sbin/ifconfig eth0 |grep \"HWaddr\" | awk '{print $5}'")
            return output[1].strip().upper()
        except:
            return self.UNKNOWN
    
    def getWANIP(self):
        try:
            cmd = "/usr/bin/curl --connect-timeout 5 -s -G " + properties.URL_WHATISMYIP
            output = executeCommand(cmd, [], True)
            wanIP = output[1].strip()
            utils = ValidationUtils()
            if utils.isValidIP(wanIP):
                return wanIP
            else:
                return self.UNKNOWN
        except:
            return self.UNKNOWN

    def int2bin(self, n, count=8):
        return "".join([str((int(n) >> y) & 1) for y in range(count-1, -1, -1)])

    def getIpBinaryArrays(self, ipaddress):
        binaryArr = []
        ipArr = ipaddress.split(".")
        for octet in ipArr:
            binaryArr.append(self.int2bin(octet))
        return ipArr, binaryArr

    def convertIP2Number(self, iparr):
        return (int(iparr[3]) + int(iparr[2]) * 256 + int(iparr[1]) * 256 * 256 + int(iparr[0]) * 256 * 256 * 256)

    def joinArr2IP(self, arr):
        return ".".join(str(i) for i in arr)

    def getOnesComplement(self, binarr):
        arr = []
        for i in binarr:
            arr.append(self.int2bin(-int(i, 2)-1))
        return arr
    
    def dhcpOptions(self):
        fd = open(properties.DHCP_CFG_DEST)
        lines = fd.read().split("\n")
        fd.close()
        details = {}
        subnet = None
        for line in lines:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            if subnet == None:
                if line.startswith("option"):
                    matched = re.match("option\s+domain-name\s+\"(.+)\";", line)
                    if matched:
                        details['domainname'] = matched.group(1)

                if  line.startswith("option"):
                    matched = re.match("option\s+domain-name-servers\s+([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\s*,\s*([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\s*;", line)
                    if matched:
                        details['dns1'] = matched.group(1)
                        details['dns2'] = matched.group(2)

                if line.startswith("subnet"):
                    matched = re.match("subnet\s+([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\s+netmask\s+([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\s+", line)
                    if matched:
                        details['subnet'] = matched.group(1)
                        details['netmask'] = matched.group(2)
                        subnet = details['subnet']

            else:
                if line == "}":
                    break
                elif line.startswith("range"):
                    matched = re.match("range\s+([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\s+([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})", line)
                    if matched:
                        details['startIP'] = matched.group(1)
                        details['endIP'] = matched.group(2)
                elif line.startswith("option"):
                    matched = re.match("option\s+routers\s+([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\s*;", line)
                    if matched:
                        details['gateway'] = matched.group(1)
                elif line.startswith("next-server"):
                    matched = re.match("next-server\s+([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\s*;", line)
                    if matched:
                        details['nextserver'] = matched.group(1)
        return details
